<template>
	<view class="preview" v-if="currentInfo">
		<swiper circular :current="currentIndex" @change=swiperChange>
			<swiper-item v-for="(item,index) in classList" :key="item._id">
				<image v-if="readImgs.includes(index)" :src="item.picurl" mode="aspectFill" @click="maskChange"></image>
			</swiper-item>
		</swiper>
		<view class="mask" v-show="maskState">
			<view class="goBack" :style="{top:getStatusBarHeight()+'px'}" @click="goBack">
				<uni-icons type="back" color="#FFF" size="20"></uni-icons>
			</view>
			<view class="count">
				{{currentIndex+1}} / {{classList.length}}
			</view>
			<view class="time">
				<uni-dateformat :date="new Date()" format="hh:mm"></uni-dateformat>
			</view>
			<view class="date">
				<uni-dateformat :date="new Date()" format="MM月dd日"></uni-dateformat>
			</view>
			<view class="footer">
				<view class="box" @click="clickInfo">
					<uni-icons type="info" size="28"></uni-icons>
					<view class="text">信息</view>
				</view>
				<view class="box" @click="clickScore">
					<uni-icons type="star" size="28"></uni-icons>
					<view class="text">
						{{currentInfo?.score}}
					</view>
				</view>
				<view class="box" @click="clickDownload">
					<uni-icons type="download" size="23"></uni-icons>
					<view class="text">
						下载
					</view>
				</view>
			</view>
		</view>
		<uni-popup type="bottom" ref="infoPopup">
			<view class="infoPopup">
				<view class="popHeader">
					<!-- 写一个空盒子，使布局能够平均分布 -->
					<view></view>
					<view class="title">壁纸信息</view>
					<view class="close">
						<uni-icons type="closeempty" size="18" color="#999" @click="clickInfoClose"></uni-icons>
					</view>
				</view>
				<scroll-view scroll-y>
					<view class="content">
						<view class="row">
							<view class="label">壁纸ID：</view>
							<text class="value" selectable>{{currentInfo?._id}}</text>
						</view>
						<!-- <view class="row">
							<view class="label">分类：</view>
							<text class="value class1">明星美女</text>
						</view>	 -->					
						<view class="row">
							<view class="label">发布者：</view>
							<text class="value">{{currentInfo?.nickname}}</text>
						</view>						
						<view class="row">
							<view class="label">评分：</view>
							<view class="value rateBox">
								<uni-rate readonly size="16" :value="currentInfo?.score"/>
								<text class="score">{{currentInfo?.score}}分</text>
							</view>
						</view>
						<view class="row">
							<view class="label">摘要：</view>
							<view class="value">{{currentInfo?.description}}</view>
						</view>	
						<view class="row">
							<view class="label">标签：</view>
							<view class="value tabs">
								<view class="tab" v-for="tab in currentInfo?.tabs" :key="tab">{{tab}}</view>
							</view>
						</view>	
						<view class="copyright">
							声明：本图片来自用户投稿，非商业使用，用于免费学习交流，如侵犯了您的权益，
							您可以拷贝壁纸ID举报至平台，邮箱513894357@qq.com，管理将删除侵权壁纸，维护您的权益。
						</view>
						<view class="safe-area-inset-bottom"></view>
					</view>
				</scroll-view>
			</view>
		</uni-popup>
		<uni-popup :is-mask-click="false" ref="scorePopup">
			<view class="scorePopup">
				<view class="popHeader">
					<view></view>
					<view class="title">{{isScore?'已经评分过了~':'壁纸评分'}}</view>
					<view class="close">
						<uni-icons type="closeempty" size="18" color="#999" @click="clickScoreClose"></uni-icons>
					</view>
				</view>
				<view class="content">
					<uni-rate allowHalf disabled-color="#ffca3e" :disabled="isScore" v-model="userScore" />
					<text class="text">{{userScore}}分</text>
				</view>
				<view class="footer">
					<button type="default" size="mini" plain :disabled="!userScore||isScore"  @click="submitScore">确认评分</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
import {getStatusBarHeight} from '@/utils/system.js'
import {apiGetSetupScore,apiWriteDownload,apiGetDetailWall} from '@/api/apis.js'
import {gotoHome} from '@/utils/common.js'
	
const maskState=ref(true)
const infoPopup=ref(null)
const scorePopup=ref(null)
const userScore=ref(0)
const isScore=ref(false)
const classList=ref([])
const currentIndex=ref(0)
const currentInfo=ref(null)
const readImgs=ref([])
//拿到本地存储中的数据赋值给storageClassList，字段进行处理后拿到大图的url再赋值给classList
const storageClassList=uni.getStorageSync('storageClassList')||[];
classList.value=storageClassList.map((item)=>{
	return {
		...item,//将除picurl以外的属性展开
		picurl:item.smallPicurl.replace("_small.webp",".jpg"),
	}
})

//onLoad钩子
onLoad(async (e)=>{
	//如果id不存在，直接返回
	// if(!e.id) gotoHome()
	//如果是分享来到预览页面，设备中没有缓存，那么需要发送网络请求获得数据
	if(e.type=='share'){
		let res=await apiGetDetailWall({id:e.id})
		// console.log(res);
		classList.value=res.data.map((item)=>{
			return {
				...item,
				picurl:item.smallPicurl.replace("_small.webp",".jpg"),
			}
		})
	}
	//根据路由传递过来的id找到该id在数组中的索引，赋值给当前索引
	currentIndex.value=classList.value.findIndex(item=>item._id==e.id)
	//拿到当前索引元素中的数据赋值给currentInfo
	currentInfo.value=classList.value[currentIndex.value]
	//把已读索引放入数组的函数
	readImgsFun()
})
//轮播图滑动的回调
const swiperChange=(e)=>{
	//当前索引赋值为当前滑动到的元素的索引值
	currentIndex.value=e.detail.current
	//拿到当前索引元素中的数据赋值给currentInfo
	currentInfo.value=classList.value[currentIndex.value]
	//把已读索引放入数组的函数
	readImgsFun()
}
//把已读索引放入数组的函数（把前一个，当下，后一个元素索引都放进数组）
function readImgsFun(){
	readImgs.value.push(
		currentIndex.value<=0?classList.value.length-1:currentIndex.value-1,
		currentIndex.value,
		currentIndex.value>=classList.value.length-1?0:currentIndex.value+1
	)
	//去重
	readImgs.value=[...new Set(readImgs.value)]
}
//点击遮罩层的回调
const maskChange=()=>{
	maskState.value=!maskState.value
}
//点击信息的回调：打开弹窗
const clickInfo=()=>{
	infoPopup.value.open()
}
//点击信息框叉号的回调：关闭弹窗
const clickInfoClose=()=>{
	infoPopup.value.close()
}
//点击评分的回调：打开弹窗
const clickScore=()=>{
	// 如果currentInfo中有userScore字段, 给userScore isScore赋值
	if(currentInfo.value.userScore){
		isScore.value=true
		userScore.value=currentInfo.value.userScore
	}
	//打开评分框
	scorePopup.value.open()
}
//点击评分框叉号的回调：关闭弹窗
const clickScoreClose=()=>{
	//userScore isScore重新初始化
	isScore.value=false
	userScore.value=0
	//关闭评分框
	scorePopup.value.close()
}
//点击提交评分
const submitScore=async ()=>{
	//打开加载框
	uni.showLoading({
		title:"加载中~"
	})
	//从当前壁纸对象解构除需要的数据（_id重新命名为wallId）
	let {classid,_id:wallId}=currentInfo.value
	//发送请求进行评分
	let res=await apiGetSetupScore({
		classid,
		wallId,
		userScore:userScore.value
	})
	//关闭加载框
	uni.hideLoading()
	//相应码为0-成功
	if(res.errCode===0){
		//提示信息
		uni.showToast({
			title:"评分成功",
			icon:"none"
		})
		//向当前索引的元素添加一个新属性，更新缓存
		classList.value[currentIndex.value].userScore=userScore.value
		uni.setStorageSync('storageClassList',classList.value)
		//关闭评分框
		clickScoreClose()
	}
}
//点击跳回去：如果是预览页返回，直接回到首页
const goBack=()=>{
	uni.navigateBack({
		success:()=>{
			
		},
		fail:(err)=>{
			uni.reLaunch({
				url:"/pages/index/index"
			})
		}
	})
}
// 点击下载的回调
const getImageInfo = (src) => {
	return new Promise((resolve, reject) => {
		uni.getImageInfo({
			src,
			success: resolve,
			fail: reject
		})
	})
}
const saveImageToAlbum = (filePath) => {
	return new Promise((resolve, reject) => {
		uni.saveImageToPhotosAlbum({
			filePath,
			success: resolve,
			fail: reject
		})
	})
}
const clickDownload = async () => {
	// #ifdef H5
	uni.showModal({
		content: "请长按保存壁纸",
		showCancel: false
	})
	// #endif
	
	// #ifndef H5
	try {
		//打开加载框
		uni.showLoading({
			title: '下载中...',
			mask: true
		})
		let {classid, _id: wallId} = currentInfo.value
		let res = await apiWriteDownload({classid, wallId})
		if (res.errCode != 0) throw res

		const imageInfo = await getImageInfo(currentInfo.value.picurl)
		try {
			const saveRes = await saveImageToAlbum(imageInfo.path)
		} catch (err) {
			//已经授权，但是自己取消保存
			if (err.errMsg === 'saveImageToPhotosAlbum:fail cancel') {
				uni.showToast({
					title: "保存失败，请点击重新下载",
					icon: "none"
				})
			} else {//还未授权，打开需要用户授权提示框的提示框
				await new Promise((resolve) => {
					uni.showModal({
						title: "授权提示",
						content: "需要授权保存相册",
						success: (res) => {
							if (res.confirm) {
								// 用户点击了“确定”，我们引导去授权设置页
								uni.openSetting({
									success: (setting) => {
										if (setting.authSetting['scope.writePhotosAlbum']) {
											// 用户在设置中打开了权限
											uni.showToast({
												title: "获取授权成功",
												icon: "none"
											})
										} else {
											// 用户在设置中没打开权限
											uni.showToast({
												title: "获取授权失败",
												icon: "none"
											})
										}
										// 不管用户选了什么，都 resolve 让流程继续下去
										resolve()
									}
								})
							} else {
								// 用户点击了“取消”，不去设置页，也要让流程继续
								resolve()
							}
						}
					})
				})
			}
		}
	} catch (err) {
		console.log(err)
	} finally {
		//关闭加载框
		uni.hideLoading()
	}
	// #endif
}
//分享给好友
onShareAppMessage((e)=>{
	return{
		title:"蝴蝶虾壁纸",
		path:"/pages/preview/preview?id="+currentInfo.value._id+"&type=share",
	}
})
//分享到朋友圈
onShareTimeline(()=>{
	return{
		title:"蝴蝶虾壁纸",
		query:"id="+currentInfo.value._id+"&type=share",
	}
})
</script>

<style lang="scss" scoped>
.preview{
	width: 100%;
	height: 100vh;
	position: relative;
	swiper{
		width: 100%;
		height: 100%;
		image{
			width: 100%;
			height: 100%;
		}
	}
	.mask{
		//子代选择器：实现公共样式的抽离
		&>view{
			//实现水平居中效果
			position: absolute;
			left: 0;
			right: 0;
			margin:auto;
			width: fit-content;
			//文字颜色
			color:#fff;
		}
		.goBack{
			width: 38px;
			height: 38px;
			margin-left:0;
			background: rgba(0,0,0,.5);
			backdrop-filter: blur(10rpx);
			left:30rpx;
			border:1rpx solid rgba(255,255,255,.3);
			border-radius: 100px;
			display: flex;
			align-items: center;
			justify-content: center;
		}
		.count{
			//定位
			top:10vh;//距离顶部的偏移量
			//盒子模型
			padding: 8rpx 28rpx;
			//磨砂效果
			background: rgba(0, 0, 0, .3);
			backdrop-filter: blur(10rpx);
			//文字大小
			font-size: 28rpx;
			//圆角
			border-radius: 40rpx;
		}
		.time{
			//定位
			top:calc(10vh + 80rpx);
			//文字大小 粗细 行高
			font-size: 140rpx;
			font-weight:100;
			lint-height:1em;
			//文字阴影
			text-shadow: 0 4rpx rgba(0, 0, 0, .3);
		}
		.date{
			//定位
			top:calc(10vh + 250rpx);
			//文字大小
			font-size:34rpx;
			//文字阴影
			text-shadow: 0 2rpx rgba(0, 0, 0, .3);
		}
		.footer{
			//定位
			bottom: 10vh;
			//盒子模型
			width: 65vw;
			height: 120rpx;
			//文字颜色
			color:#000;
			//圆角 文字阴影
			border-radius: 120rpx;
			box-shadow: 0 2rpx 0 rgba(0, 0, 0, .1);
			//磨砂效果
			background:rgba(255,255,255,.8);
			backdrop-filter: blur(20rpx);
			//弹性布局
			display: flex;
			justify-content: space-around;
			align-items: center;
			.box{
				//盒子模型
				padding: 2rpx 12rpx;//让文字和图标和父级盒子有点距离，可以让触碰区域变大，用户体验感更好！
				// border:1px solid red;
				//弹性布局
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				.text{
					font-size:26rpx;
					color: $text-font-color-2;
				}
			}
		}
	}
	// 两个弹窗公用一个头部
	.popHeader{
		display: flex;
		justify-content: space-between;
		align-items: center;
		.title{
			color:$text-font-color-2;
			font-size: 26rpx;
		}
		.close{
			padding: 6rpx;//让触摸区域变大
			// border: 1px solid red;
		}
	}
	.infoPopup{
		//盒子模型
		padding: 30rpx;//让弹窗内容和最外层父盒子有点距离，更加美观！
		//背景颜色
		background: #fff;
		//圆角
		border-radius: 30rpx 30rpx 0 0;
		overflow: hidden;//给父级盒子加圆角需要加这句话
		scroll-view{
			//最大高度
			max-height: 60vh;//最高为屏幕宽度的60%，超出使用滚动条
			.content{
				.row{
					display: flex;
					padding: 16rpx 0;
					font-size: 32rpx;
					line-height: 1.7em;
					.label{
						width: 140rpx;
						color:$text-font-color-3;
						font-size: 30rpx;
						text-align: right;
					}
					.value{
						flex:1;
						width: 0;//防止.value内容太长把.label标签挤压成多行
					}
					.rateBox{
						display: flex;
						align-items: center;
						.score{
							font-size: 26rpx;
							color:$text-font-color-2;
							padding-left: 10rpx;
						}
					}
					.tabs{
						display: flex;
						flex-wrap: wrap;//自动换行
						.tab{
							line-height: 1em; 
							padding: 10rpx 30rpx;
							margin: 0 10rpx 10rpx 0;
							font-size: 22rpx;
							color: $brand-theme-color;
							border:1px solid $brand-theme-color;
							border-radius: 40rpx;
						}
					}
					// .class1{
					// 	color: $brand-theme-color;
					// }
				}
				.copyright{
					line-height: 1.6em;
					padding: 20rpx;
					margin: 20rpx 0;
					font-size: 28rpx;
					color: #666;
					background: #f6f6f6;
					border-radius: 10rpx;
				}
			}
		}
	}
	.scorePopup{
		width: 70vw;
		padding: 30rpx;
		background: #fff;
		border-radius: 30rpx;
		.content{
			padding: 30rpx 0;
			display: flex;
			justify-content: center;
			align-items: center;
			.text{
				width: 80rpx;
				padding-left: 10rpx;
				color: #ffca3e;
				line-height: 1em;
				text-align: right;
			}
		}
		.footer{
			padding: 10rpx 0;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
}
</style>
